<template>
  <div class="app-container">
    <el-form :model="loginForm">
      <el-form-item label="手机号">
        <el-input v-model="loginForm.mobile" placeholder="请输入手机号">
          <template #append>
            <el-button type="primary" @click="handleSendCode">发送验证码</el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="验证码">
        <el-input v-model="loginForm.checkCode" placeholder="请输入验证码"></el-input>
      </el-form-item>
      <el-button type="primary" @click="handleReceive">立即领取</el-button>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { sendLoginNoByPhone, loginByPhoneCode } from '@/api/user/user'
import { receiveCoupons } from '@/api/coupon/coupon'

defineOptions({
  name: 'CouponsReceive'
})

const route = useRoute()

interface LoginForm {
  mobile: string | null
  checkCode: string | null
  devicetype: number
}

interface ReceiveForm {
  qrCodeId: string | null
  userId: number
  couponsId: string | null
}

const loginForm = reactive<LoginForm>({
  mobile: null,
  checkCode: null,
  devicetype: 1
})

const receiveForm = reactive<ReceiveForm>({
  qrCodeId: route.query.id as string || null,
  userId: 1369967467052400640,
  couponsId: route.query.couponsId as string || null
})

// 发送验证码
const handleSendCode = () => {
  if (!loginForm.mobile) {
    ElMessage.error('请输入手机号')
    return
  }
  
  sendLoginNoByPhone({ telPhone: loginForm.mobile, devicetype: 1 }).then(res => {
    if (res.code == 200) {
      ElMessage.success(res.msg)
    } else {
      ElMessage.error(res.msg)
    }
  }).catch(e => {
    console.error(e)
  })
}

// 立即领取
const handleReceive = () => {
  receiveCoupons(receiveForm).then(res => {
    if (res.code == 200) {
      ElMessage.success(res.msg)
      // TODO 唤起微信小程序
    } else {
      ElMessage.error(res.msg)
    }
  }).catch(e => {
    console.error(e)
  })
}
</script>

<style scoped lang="scss">

</style>
